package _11_整理题目._6_模拟设计._计算器;

import org.junit.Test;

import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/basic-calculator-ii/
 *
 */
public class _01_计算器_加减乘除 {

    public int calculate(String s) {
        String str = s.replaceAll(" ", "");
        int n = str.length();
        Stack<Integer> stack = new Stack<>();

        char preSign = '+';
        int num = 0;
        for (int i = 0; i < n; i++) {
            if (Character.isDigit(str.charAt(i))) {
                num = num * 10 + (str.charAt(i)-'0');
            }
            if (!Character.isDigit(str.charAt(i)) || i==n-1) {
                switch (preSign) {
                    case '+':
                        stack.push(num);
                        break;
                    case '-':
                        stack.push(-num);
                        break;
                    case '*':
                        stack.push(stack.pop() * num);
                        break;
                    default:
                        stack.push(stack.pop() / num);
                }
                preSign = str.charAt(i);
                num = 0;
            }
        }
        int ans = 0;
        while (!stack.isEmpty()) {
            ans += stack.pop();
        }
        return ans;
    }

    @Test
    public void main() {
        String s = " 3+5 / 2 ";
        System.out.println(calculate(s));
    }

}
